#include "stdafx.h"
#include "Holders.h"

RapiStreamHolder::RapiStreamHolder()
{
    m_RapiStream = NULL;
}

IRAPIStream *RapiStreamHolder::Stream()
{
    return m_RapiStream;
}

HRESULT RapiStreamHolder::Invoke(const std::wstring &pathToDll,
                                 const std::wstring &funcName,
                                 const std::wstring &input,
                                 BYTE *output,
                                 DWORD outputSize)
{
    HRESULT result = S_OK;

    result = CeRapiInvoke(pathToDll.c_str(),
                          funcName.c_str(),
                          input.size() * sizeof(wchar_t),
                          (BYTE*)input.c_str(),
                          &outputSize,
                          (BYTE**)output,
                          &m_RapiStream,
                          0);
    return result;
}

HRESULT RapiStreamHolder::SetReadTimeout(DWORD timeout)
{
    HRESULT result = S_OK;
    
    result = m_RapiStream->SetRapiStat(STREAM_TIMEOUT_READ, timeout);

    return result;
}

RapiStreamHolder::~RapiStreamHolder()
{   
    if(m_RapiStream != NULL)
        m_RapiStream->Release();
}

HRESULT RegKeyHolder::OpenKey(HKEY preDefKey, const std::wstring &subKey)
{
    HRESULT result = S_OK;
    int retValue = 0;

    retValue = RegOpenKeyEx(preDefKey,
                            subKey.c_str(),
                            0, 
                            KEY_READ,
                            &m_Key);

    if(retValue != ERROR_SUCCESS)
        result = S_FALSE;

    return result;
}

HRESULT RegKeyHolder::GetKeyValue(const std::wstring &valueName,
                                  BYTE *valueBuffer,
                                  DWORD valueSize)
{
    HRESULT result = S_OK;
    int retValue = 0;

    retValue = RegQueryValueEx(m_Key,
                               valueName.c_str(),
                               NULL,
                               NULL,
                               valueBuffer,
                               &valueSize);
    if(retValue != ERROR_SUCCESS)   
        result = S_FALSE;

    return result;
}

RegKeyHolder::~RegKeyHolder()
{
    RegCloseKey(m_Key); 
}

HRESULT CeFindHolder::FirstFile(const std::wstring &path, CE_FIND_DATA &fileSystemItem)
{
    HRESULT result = S_OK;

    m_FileHandle = CeFindFirstFile(path.c_str(), &fileSystemItem);

    if(m_FileHandle == INVALID_HANDLE_VALUE)
        result = S_FALSE;

    return result;
}

CeFindHolder::~CeFindHolder()
{
    CeFindClose(m_FileHandle);
}